import axios from 'axios'

export default {
  namespaced: true,
  state() {
    return {
      list: []
    }
  },
  mutations: {
    updateList(state, payload) {
      state.list = payload
    }
  },
  actions: {
    async getList(ctx) {
      const res = await axios.get('http://192.168.87.210:9999/cart')
      ctx.commit('updateList', res.data)
    },
    async syncCount(ctx, obj) {
      const res = await axios.patch('http://192.168.87.210:9999/cart/' + obj.id, {
        count: obj.count
      })
    }
  },
  getters: {
    totalPrice(state) {
      return state.list.reduce((pre, cur) => {
        return pre + cur.count * cur.price
      }, 0)
    },
    totalCount(state) {
      return state.list.reduce((pre, cur) => {
        return pre + cur.count
      }, 0)
    }
  }
}